package Controller.user;

import java.io.IOException;
import Services.WebService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import Controller.BaseHttpServlet;
import Entity.User;
import Services.WebService;

public class LoginServlet extends BaseHttpServlet {
    @Override
    protected void processRequest(HttpServletRequest request, HttpServletResponse response, WebService webServices, String action) throws ServletException, IOException {
    	if(webServices.getCurrentUser() != null){
    		response.sendRedirect("/member");
    	} else if (action == null) {
			this.forward(request, response, webServices, action, "/auth/login.jsp");
		} else if (action.equals("login_check")) {
			String username = request.getParameter("username");
			String password = request.getParameter("password"); 
			
			if(request.getMethod() == "POST" && username != null && password != null){
				User loginUser = new User();
				loginUser.setUsername(username);
				loginUser.setPassword(password);
				
				loginUser = webServices.getEntityManager().authentication(loginUser);
				
				if(loginUser != null){
					webServices.setCurrentUser(loginUser);
					action = "succeeded";
					request.getSession().setAttribute("userID", loginUser.getId());

					this.forward(request, response, webServices, action, "/auth/login.jsp");
				} else {
					this.loginFail(request, response, webServices, action, username);					
				}
			} else {
				this.loginFail(request, response, webServices, action, username);
			}
		}
    }

	private void loginFail(HttpServletRequest request, HttpServletResponse response, WebService webServices, String action, String username) {
		username = username == null?"":username;
		action = "failed";
		request.setAttribute("input.username", username);
		this.forward(request, response, webServices, action, "/auth/login.jsp");
	}
}
